import React, { useEffect, useRef, useState } from "react";
import { Service } from "@/lib";
import { Flex, message, Upload, Button, Image } from 'antd';
import type { GetProp, UploadProps } from 'antd';
import { shouldSplitToUpload, UploadSplit } from "../ResourceList/UploadSplit";

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
type UploadFile = Parameters<GetProp<UploadProps, 'onChange'>>[0]['file'];

type UploadStatus = "uploading" | "done" | "removed"|"error"|"progress";

interface IUploadProps {
    onChange?: (fileUrl: string, fileList: UploadFile[]) => void;
    children?: any;
    fileList?: any[];
    showUploadList?: boolean;
    value?: string;
    onStatusChange?: (status: UploadStatus, sourceUrl?: string, file?: FileType) => void;
    validate?: (file: File) => boolean;
}
const getBase64 = (img: FileType, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };
  
const VideoContentType = [
"video/mp4", "video/x-msvideo", "video/webm","video/flv","video/avi","video/mov", "video/ogg",
"audio/mp3","audio/mpeg","audio/wav","audio/mp4",
"application/pdf"
];
const UploadAction = (props: IUploadProps) => {
    const serviceApi = Service.useService();
    const uploadAction = serviceApi.getUrl("resource.upload") as string;
    const reviewUrl = serviceApi.getUrl("resource.mediaUrl") as string;
    const [ updateStatus ] = useState({
      mount: false,
      isUploading: false
    })
    const currentFile = useRef<any>({
        uid: null
    });
    const beforeUpload = (file: FileType) => {
        const isJpgOrPng = ["image/jpeg","image/png","image/gif", "image/bmp", "image/jpg"].includes(file.type);
        const isVideo = VideoContentType.includes(file.type);
        currentFile.current.uid = file.uid;console.log(file.type);
        if (!isJpgOrPng && !isVideo) {
          message.error('不支持的文件类型。');
          return false;
        }
        const isLt2M = file.size / 1024 / 1024 < 900;
        const needsSplitUpload = shouldSplitToUpload(file);
        if (!isLt2M) {
          message.error('文件大小超出限制MB!');
          return false;
        }
        if(props.validate && !props.validate(file)) {
          message.error("上传文件大小超出限制或不允许的文件类型。");
          return false;
        }
        if(needsSplitUpload) {
          const upload = new UploadSplit({
            file,
            blockSize: 1024 * 1024 * 2,
            service: serviceApi,
            onFailed: () => {
              message.error('文件上传失败');
              typeof props.onStatusChange === "function" && props.onStatusChange("error");
            },
            onSuccess: (resp: any) => {
              const sourceUrl = resp?.data?.url || resp?.data?.id;
              typeof props.onStatusChange === "function" && props.onStatusChange("done", sourceUrl, [{
                response: resp,
                uid: resp?.data?.id,
                name: file.name,
                size: file.size,
                status: 'done'
              }] as any);
            },
            onProgress: ({ percent }: any) => {
              if(!updateStatus.mount) {
                upload.start
              }
                typeof props.onStatusChange === "function" && props.onStatusChange("progress", currentFile.current.uid, {
                    percent: percent
                } as any);
            }
          });
          typeof props.onStatusChange === "function" && props.onStatusChange("uploading");
          upload.start();
        }
        return (isJpgOrPng || isVideo) && isLt2M && !needsSplitUpload;
      };

    const handleChange: UploadProps['onChange'] = (info) => {
  
      if (info.file.status === 'uploading') {
        typeof props.onStatusChange === "function" && props.onStatusChange("uploading", currentFile.current.uid, {
            percent: info.file.percent
        } as any);
        return;
      }
      info.event
      if (info.file.status === 'done') {
        const sourceUrl = info.file.response?.data?.url || info.file.response?.data?.id;
        typeof props.onStatusChange === "function" && props.onStatusChange("done", sourceUrl, info.file.originFileObj as FileType);
      } else if(info.file.status === "removed") {
        typeof props.onStatusChange === "function" && props.onStatusChange("removed", info.fileList as any);
      }
    };
    useEffect(() => {
      updateStatus.mount = true;
      return () => {
        updateStatus.mount = false;
      };
    }, [])
    return (<>
        <Upload
                name="file"
                // listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={uploadAction}
                beforeUpload={beforeUpload}
                onChange={handleChange}
              
                // maxCount={1}
                // fileList={fileList}
                // defaultFileList={fileList}
                withCredentials
              >
            {props.children}
        </Upload>
    </>);
};

export default UploadAction;
